package com.punai.customer.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punai.common.core.domain.entity.SysDictData;
import com.punai.common.utils.DictUtils;
import com.punai.common.utils.SecurityUtils;
import com.punai.customer.domain.CusExpenseCategories;
import com.punai.customer.domain.vo.CusLinkGkVo;
import com.punai.customer.mapper.CusExpenseCategoriesMapper;
import com.punai.customer.mapper.CusGxLinkGkCategoriesMapper;
import com.punai.customer.service.ICusExpenseCategoriesService;
import com.punai.gk.domain.vo.SimplifyVo;
import com.punai.gk.mapper.GkUseDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 费用项类别Service业务层处理
 *
 * @author zxw
 * @date 2022-12-04
 */
@Service
public class CusExpenseCategoriesServiceImpl extends ServiceImpl<CusExpenseCategoriesMapper,CusExpenseCategories> implements ICusExpenseCategoriesService
{
    @Autowired
    private CusExpenseCategoriesMapper cusExpenseCategoriesMapper;
    @Autowired
    private CusGxLinkGkCategoriesMapper cusGxLinkGkCategoriesMapper;
    @Autowired
    private GkUseDataMapper gkUseDataMapper;

    /**
     * 查询费用项类别
     *
     * @param id 费用项类别主键
     * @return 费用项类别
     */
    @Override
    public CusExpenseCategories selectCusExpenseCategoriesById(String id)
    {
        return cusExpenseCategoriesMapper.selectCusExpenseCategoriesById(id, SecurityUtils.getCompanyId());
    }

    /**
     * 查询费用项类别列表
     *
     * @param cusExpenseCategories 费用项类别
     * @return 费用项类别
     */
    @Override
    public List<CusExpenseCategories> selectCusExpenseCategoriesList(CusExpenseCategories cusExpenseCategories)
    {
        return cusExpenseCategoriesMapper.selectCusExpenseCategoriesList(cusExpenseCategories);
    }

    @Override
    public List<CusExpenseCategories> selectListGk(CusExpenseCategories cusExpenseCategories) {
        List<CusExpenseCategories> cusExpenseCategoriesList = cusExpenseCategoriesMapper.selectCusExpenseCategoriesList(cusExpenseCategories);
//        cusExpenseCategoriesList.forEach(item -> item.setLinkGkMap(JSON.parseObject(item.getGkItem(), Map.class)));

        List<SimplifyVo> simplifyVos = gkUseDataMapper.selectIdNameList(cusExpenseCategories.getCompanyId());
        Map<String, String> idNameMap = simplifyVos.stream().collect(Collectors.toMap(SimplifyVo::getId, SimplifyVo::getName));

        for (CusExpenseCategories expenseCategories : cusExpenseCategoriesList) {
            String gkItem = expenseCategories.getGkItem();
            if (StrUtil.isEmpty(gkItem)) {
                continue;
            }
            Map<String, List<String>> gkItemMap = JSON.parseObject(gkItem, Map.class);
            expenseCategories.setLinkGkMap(gkItemMap);
            Map<String, LinkedHashMap<String, String>> idAndNameMap = new HashMap<>();
            for (Map.Entry<String,List<String>> entry: gkItemMap.entrySet()) {
                String gkCategory = entry.getKey();
                List<String> gkIds = entry.getValue();
                gkIds.forEach(gkId ->{
                    String name = idNameMap.get(gkId);
                    if(idAndNameMap.containsKey(gkCategory)){
                        idAndNameMap.get(gkCategory).put(gkId,name);
                    }else {
                        idAndNameMap.put(gkCategory,new LinkedHashMap<>());
                        idAndNameMap.get(gkCategory).put(gkId,name);
                    }
                });
            }
            expenseCategories.setLinkGkMapName(idAndNameMap);
        }
        return cusExpenseCategoriesList;
    }

    /**
     * 新增费用项类别
     *
     * @param cusExpenseCategories 费用项类别
     * @return 结果
     */
    @Override
    public int insertCusExpenseCategories(CusExpenseCategories cusExpenseCategories)
    {
            return cusExpenseCategoriesMapper.insert(cusExpenseCategories);
    }

    /**
     * 修改费用项类别
     *
     * @param cusExpenseCategories 费用项类别
     * @return 结果
     */
    @Override
    public int updateCusExpenseCategories(CusExpenseCategories cusExpenseCategories)
    {
        return cusExpenseCategoriesMapper.updateById(cusExpenseCategories);
    }

    @Override
    @Transactional
    public int updateCategorieLinkGk(Long companyId, CusLinkGkVo cusLinkGkVo) {
        String id = cusLinkGkVo.getId();
        String gkCategory = cusLinkGkVo.getCategory();
        List<String> gkIdNews = cusLinkGkVo.getGkIds();

        CusExpenseCategories cusExpenseCategories = cusExpenseCategoriesMapper.selectCusExpenseCategoriesById(id, companyId);

        LinkedHashMap<String, List<String>> gkItemMap = JSON.parseObject(cusExpenseCategories.getGkItem(), LinkedHashMap.class);
        List<String> gkIdOlds = gkItemMap.get(gkCategory);

        gkItemMap.put(gkCategory, gkIdNews);
        cusExpenseCategories.setGkItem(JSON.toJSONString(gkItemMap));

        LambdaQueryWrapper<CusExpenseCategories> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CusExpenseCategories::getId, id);
        wrapper.eq(CusExpenseCategories::getCompanyId, companyId);
        cusExpenseCategoriesMapper.update(cusExpenseCategories, wrapper);

        List<String> delIds = gkIdOlds.stream().filter(item -> !gkIdNews.contains(item)).collect(Collectors.toList());
        for (String delId : delIds) {
            cusGxLinkGkCategoriesMapper.delLinkGkId(delId,id,companyId);
        }
        return 200;
    }

    @Override
    @Transactional
    public int deleteCategorieLinkGk(Long companyId, CusLinkGkVo cusLinkGkVo) {
        String id = cusLinkGkVo.getId();
        String gkCategory = cusLinkGkVo.getCategory();
        String gkId = cusLinkGkVo.getGkId();

        CusExpenseCategories cusExpenseCategories = cusExpenseCategoriesMapper.selectCusExpenseCategoriesById(id, companyId);

        LinkedHashMap<String, List<String>> gkItemMap = JSON.parseObject(cusExpenseCategories.getGkItem(), LinkedHashMap.class);
        List<String> gkIds = gkItemMap.get(gkCategory);
        gkIds.remove(gkId);
        gkItemMap.put(gkCategory,gkIds);
        cusExpenseCategories.setGkItem(JSON.toJSONString(gkItemMap));

        LambdaQueryWrapper<CusExpenseCategories> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CusExpenseCategories::getId,id);
        wrapper.eq(CusExpenseCategories::getCompanyId,companyId);
        cusExpenseCategoriesMapper.update(cusExpenseCategories,wrapper);
        cusGxLinkGkCategoriesMapper.delLinkGkId(gkId,id,companyId);
        return 200;
    }

    /**
     * 批量删除费用项类别
     *
     * @param ids 需要删除的费用项类别主键
     * @return 结果
     */
    @Override
    public int deleteCusExpenseCategoriesByIds(String[] ids)
    {
        return cusExpenseCategoriesMapper.deleteCusExpenseCategoriesByIds(ids);
    }

    /**
     * 删除费用项类别信息
     *
     * @param id 费用项类别主键
     * @return 结果
     */
    @Override
    public int deleteCusExpenseCategoriesById(String id)
    {
        return cusExpenseCategoriesMapper.deleteCusExpenseCategoriesById(id);
    }

    @Override
    public List<CusExpenseCategories> getExpenseCategoriesListByNoIds(Long companyId,List<String> noInIds) {
        List<CusExpenseCategories> result = cusExpenseCategoriesMapper.selectExpenseCategoriesListByNoIds(companyId,noInIds);
        return result;
    }

    @Override
    public List<CusExpenseCategories> getByNameSearchCJ(String name, Long companyId, List<String> noInIds) {
        return cusExpenseCategoriesMapper.selectCusExpenseCategoriesListCJ(name, companyId, noInIds);
    }

    @Override
    @Transactional
    public int clearLinkGk(String id, Long companyId) {
        Map<String,List<String>> dictMap = new HashMap<>();
        Map<String,String> dictStrMap = new HashMap<>();

        List<SysDictData> gk_categorys = DictUtils.getDictCache("gk_categorys");
        for (SysDictData sysDictData : gk_categorys) {
            dictMap.put(sysDictData.getDictValue(),new ArrayList<>());
            dictStrMap.put(sysDictData.getDictValue(),"");
        }
        // 置空被标准费用项关联的类别
        cusGxLinkGkCategoriesMapper.clearLinkGkItemByCategorieId(JSON.toJSONString(dictStrMap),id,companyId);
        // 置空类别
        CusExpenseCategories cusExpenseCategories = new CusExpenseCategories();
        cusExpenseCategories.setGkItem(JSON.toJSONString(dictMap));
        LambdaQueryWrapper<CusExpenseCategories> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CusExpenseCategories::getId,id);
        wrapper.eq(CusExpenseCategories::getCompanyId,companyId);
        return cusExpenseCategoriesMapper.update(cusExpenseCategories,wrapper);
    }

    @Override
    public List<SimplifyVo> getGkItemById(String id, String gkType) {
        Long companyId = SecurityUtils.getCompanyId();
        String gkItem = cusExpenseCategoriesMapper.getGkItemById(id,companyId, gkType);
        List<String> gkIds = JSON.parseArray(gkItem).toList(String.class);
        if(CollUtil.isEmpty(gkIds)){
            return null;
        }
        return gkUseDataMapper.getSimplifyVoByIds(gkIds, companyId);
    }
}
